<script setup lang="ts">
import ObsImage from '#/components/obsImage.vue';
import dashLineImg from '#/assets/images/dash-line.png';
import triangleImg from '#/assets/images/triangle.png';
import CustomPopover from '#/components/custom-popover.vue';
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';

const props = defineProps({
  processNode: {
    type: Object,
    required: true
  }
})

// 拖拽滚动相关状态
const nodeWar = ref<HTMLElement>();
const isDragging = ref(false);
const startX = ref(0);
const scrollLeft = ref(0);
let resizeObserver: ResizeObserver | null = null;

// 容器是否已准备好（外部样式已确定）
const isContainerReady = ref(false);

// 计算是否需要显示箭头按钮
const shouldShowArrows = computed(() => {
  if (!nodeWar.value || !isContainerReady.value) return false;
  return nodeWar.value.scrollWidth > nodeWar.value.clientWidth;
});

// 检查滚动状态
const checkScrollStatus = () => {
  if (!nodeWar.value) return;
  
  const { scrollLeft: currentScrollLeft, scrollWidth, clientWidth } = nodeWar.value;
  scrollLeft.value = currentScrollLeft;
  
  // 确保容器宽度已经稳定（不为0）
  if (clientWidth === 0) {
    // 如果容器宽度为0，说明还没有完全渲染，延迟重试
    setTimeout(() => {
      checkScrollStatus();
    }, 100);
    return;
  }
  
  // 更新按钮显示状态
  showLeftArrow.value = currentScrollLeft > 0;
  showRightArrow.value = currentScrollLeft < scrollWidth - clientWidth - 1;
};

// 按钮显示状态
const showLeftArrow = ref(false);
const showRightArrow = ref(false);

// 滚动到指定方向
const scrollTo = (direction: 'left' | 'right') => {
  if (!nodeWar.value) return;
  
  const scrollDistance = 120; // 每次滚动120px
  const currentScrollLeft = nodeWar.value.scrollLeft;
  const targetScrollLeft = direction === 'left' 
    ? Math.max(0, currentScrollLeft - scrollDistance)
    : currentScrollLeft + scrollDistance;
  
  nodeWar.value.scrollTo({
    left: targetScrollLeft,
    behavior: 'smooth'
  });
};



// 开始拖拽
const handleMouseDown = (e: MouseEvent) => {
  if (!nodeWar.value) return;
  
  isDragging.value = true;
  startX.value = e.pageX - nodeWar.value.offsetLeft;
  scrollLeft.value = nodeWar.value.scrollLeft;
  
  // 添加拖拽样式
  nodeWar.value.style.cursor = 'grabbing';
  nodeWar.value.style.userSelect = 'none';
};

// 拖拽中
const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value || !nodeWar.value) return;
  
  e.preventDefault();
  const x = e.pageX - nodeWar.value.offsetLeft;
  const walk = (x - startX.value) * 2; // 滚动速度倍数
  nodeWar.value.scrollLeft = scrollLeft.value - walk;
};

// 结束拖拽
const handleMouseUp = () => {
  if (!nodeWar.value) return;
  
  isDragging.value = false;
  nodeWar.value.style.cursor = 'grab';
  nodeWar.value.style.userSelect = 'auto';
  
  // 检查滚动状态
  checkScrollStatus();
};

// 鼠标离开容器
const handleMouseLeave = () => {
  if (isDragging.value) {
    handleMouseUp();
  }
};

// 监听滚动事件
const handleScroll = () => {
  checkScrollStatus();
};

// 检查外部容器是否已准备好
const checkContainerReady = () => {
  if (!nodeWar.value) return false;
  
  // 检查当前容器
  if (nodeWar.value.clientWidth === 0) return false;
  
  // 检查父容器
  const parentContainer = nodeWar.value.parentElement;
  if (parentContainer && parentContainer.clientWidth === 0) return false;
  
  // 检查祖父容器（processNode容器）
  const grandParentContainer = parentContainer?.parentElement;
  if (grandParentContainer && grandParentContainer.clientWidth === 0) return false;
  
  return true;
};

onMounted(() => {
  // 组件挂载后设置初始样式
  if (nodeWar.value) {
    nodeWar.value.style.cursor = 'grab';
  }
  
  // 设置 ResizeObserver 监听容器大小变化
  if (nodeWar.value && window.ResizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      nextTick(() => {
        checkScrollStatus();
      });
    });
    resizeObserver.observe(nodeWar.value);
  }
  
  // 等待外部容器样式和宽度确定后再检查滚动状态
  const waitForContainerReady = () => {
    if (checkContainerReady()) {
      isContainerReady.value = true;
      checkScrollStatus();
    } else {
      // 如果容器还没有准备好，延迟重试
      setTimeout(() => {
        waitForContainerReady();
      }, 100);
    }
  };
  
  // 开始等待容器准备就绪
  setTimeout(() => {
    waitForContainerReady();
  }, 200);
});

// 监听数据变化，重新检查滚动状态
watch(() => props.processNode.processNodeConfigs, () => {
  nextTick(() => {
    setTimeout(() => {
      // 确保容器准备好后再检查
      if (isContainerReady.value) {
        checkScrollStatus();
      } else {
        // 如果容器还没有准备好，等待容器准备就绪
        const waitForContainerReady = () => {
          if (checkContainerReady()) {
            isContainerReady.value = true;
            checkScrollStatus();
          } else {
            setTimeout(() => {
              waitForContainerReady();
            }, 100);
          }
        };
        waitForContainerReady();
      }
    }, 100);
  });
}, { deep: true });

onUnmounted(() => {
  // 清理事件监听
  document.removeEventListener('mouseup', handleMouseUp);
  document.removeEventListener('mousemove', handleMouseMove);
  
  // 清理 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
});
</script>

<template>
  <div class="w-full bg-[#fff] rounded-[16px] p-[24px] text-center relative">
    <!-- 左箭头按钮 -->
    <div v-if="shouldShowArrows && showLeftArrow" 
      class="absolute left-2 top-1/2 -translate-y-1/2 z-10 w-8 h-8 bg-white rounded-full shadow-md flex items-center justify-center cursor-pointer hover:bg-gray-50 transition-all duration-200"
      @click="scrollTo('left')">
      <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
      </svg>
    </div>

    <!-- 右箭头按钮 -->
    <div v-if="shouldShowArrows && showRightArrow" 
      class="absolute right-2 top-1/2 -translate-y-1/2 z-10 w-8 h-8 bg-white rounded-full shadow-md flex items-center justify-center cursor-pointer hover:bg-gray-50 transition-all duration-200"
      @click="scrollTo('right')">
      <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
      </svg>
    </div>

    <div class="w-full overflow-hidden">
      <div 
        ref="nodeWar" 
        id="nodeWar" 
        class="flex items-center overflow-x-auto scrollbar-hide p-2 drag-scroll"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseLeave"
        @scroll="handleScroll">
        <div v-for="(item, index) in props.processNode.processNodeConfigs" :key="item.id"
          class="flex-shrink-0 flex items-center">
          <!-- 步骤内容 -->
          <div class="flex items-center">
            <!-- 圆形图标 -->
            <div
              class="flex-none w-[48px] h-[48px] rounded-full overflow-hidden bg-gradient-to-br from-blue-100 to-blue-200 flex items-center justify-center mr-2 shadow-sm">
              <ObsImage v-if="item.icon" :src="item.icon" :showPreview="false"
                :imgStyle="{ width: '48px', height: '48px', objectFit: 'contain' }" />
            </div>

            <!-- 文字内容 -->
            <div class="flex flex-col flex-shrink-0 max-w-[120px] text-left">
              <div :style="{
                color: item?.mainTextFormatConfigs?.fontColor,
                fontSize: item?.mainTextFormatConfigs?.fontSize + 'px',
                fontWeight: item?.mainTextFormatConfigs?.fontBold ? 'bold' : 'normal',
                fontStyle: item?.mainTextFormatConfigs?.italic ? 'italic' : 'normal',
                textDecoration: item?.mainTextFormatConfigs?.underline ? 'underline' : 'none'
              }" class="font-medium">{{ item.mainTitle }}</div>
              <div v-if="item.subTitle" class="pt-[4px] text-ellipsis-2" :style="{
                color: item?.subTextFormatConfigs?.fontColor,
                fontSize: item?.subTextFormatConfigs?.fontSize + 'px',
                fontWeight: item?.subTextFormatConfigs?.fontBold ? 'bold' : 'normal',
                fontStyle: item?.subTextFormatConfigs?.italic ? 'italic' : 'normal',
                textDecoration: item?.subTextFormatConfigs?.underline ? 'underline' : 'none'
              }">
                <CustomPopover :strTxt="item.subTitle"></CustomPopover>
              </div>
            </div>
          </div>

          <!-- 连接箭头 -->
          <div v-if="index < props.processNode.processNodeConfigs.length - 1" class="flex items-center mx-3">
            <div class="w-16 h-[2px] bg-no-repeat bg-center bg-cover"
              :style="{ backgroundImage: `url(${dashLineImg})` }"></div>
            <div class="w-3 h-3 bg-no-repeat bg-center bg-cover" :style="{ backgroundImage: `url(${triangleImg})` }">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 自定义样式
.bg-gradient-to-br {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
}

.shadow-sm {
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

// 隐藏滚动条
.scrollbar-hide {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
  &::-webkit-scrollbar {
    display: none;  /* Chrome, Safari and Opera */
  }
}

// 拖拽滚动样式
.drag-scroll {
  transition: cursor 0.2s ease;
  
  &:hover {
    cursor: grab;
  }
  
  &:active {
    cursor: grabbing;
  }
}

// 箭头按钮样式
.absolute {
  transition: all 0.2s ease-in-out;
  
  &:hover {
    transform: translateY(-50%) scale(1.05);
  }
}

// 两行文本省略号样式
.text-ellipsis-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
}
</style>
